package com.example.langchain4j.controller;

import com.example.langchain4j.common.Result;
import com.example.langchain4j.service.DifyChangeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

@RestController
@RequestMapping("/api/dify")
@Tag(name = "dify整合接口")
@Slf4j
public class DifyChangeController {

    @Resource
    private DifyChangeService difyChangeService;

    @Resource
    private com.example.langchain4j.service.AdminPunishmentNoticeService adminPunishmentNoticeService;

    private static final String GENERATED_DIR = "src/main/resources/generated";

    // 生成立案审批表
    @Operation(summary = "生成立案审批表")
    @PostMapping("/generation-shepibiao")
    public Result<Map<String, Object>> generationShenpibiao(@RequestParam("file1") MultipartFile file1,
                                       @RequestParam("file2") MultipartFile file2,
                                       HttpServletResponse response) {
        try {
            Map<String, Object> result = difyChangeService.generationShenpibiao(file1, file2, response);
            return Result.success(result);
        } catch (Exception e) {
            log.error("生成立案审批表失败", e);
            return Result.error("生成立案审批表失败: " + e.getMessage());
        }
    }

    // 生成笔录 - 使用JSON数据
    @Operation(summary = "生成笔录（使用JSON数据）")
    @PostMapping("/generation-bilu")
    public Result<Map<String, Object>> generationBilu(@RequestBody Map<String, String> request,
                                 HttpServletResponse response) {
        try {
            String jsonData = request.get("jsonData");
            if (jsonData == null || jsonData.isEmpty()) {
                return Result.error("缺少立案审批表JSON数据");
            }

            Map<String, Object> result = difyChangeService.generationBilu(jsonData, response);
            return Result.success(result);
        } catch (Exception e) {
            log.error("生成笔录失败", e);
            return Result.error("生成笔录失败: " + e.getMessage());
        }
    }

    // 生成笔录 - 从文件（保留兼容性）
    @Operation(summary = "生成笔录（从文件）")
    @PostMapping("/generation-bilu-from-file")
    public Result<Map<String, Object>> generationBiluFromFile(@RequestParam("file1") MultipartFile file1,
                                 HttpServletResponse response) {
        try {
            Map<String, Object> result = difyChangeService.generationBiluFromFile(file1, response);
            return Result.success(result);
        } catch (Exception e) {
            log.error("生成笔录失败", e);
            return Result.error("生成笔录失败: " + e.getMessage());
        }
    }

    // 生成行政处罚告知笔录
    @Operation(summary = "生成行政处罚告知笔录")
    @PostMapping("/generation-gaozhi")
    public Result<Map<String, Object>> generationGaozhi(@RequestBody Map<String, String> request,
                                                        HttpServletResponse response) {
        try {
            String jsonData = request.get("jsonData");
            String gaozhiType = request.get("gaozhiType"); // "处罚前告知" 或 "听证告知"

            if (jsonData == null || jsonData.isEmpty()) {
                return Result.error("缺少立案审批表JSON数据");
            }

            if (gaozhiType == null || gaozhiType.isEmpty()) {
                return Result.error("缺少告知类型参数");
            }

            if (!gaozhiType.equals("处罚前告知") && !gaozhiType.equals("听证告知")) {
                return Result.error("告知类型参数错误，必须是\"处罚前告知\"或\"听证告知\"");
            }

            Map<String, Object> result = adminPunishmentNoticeService.generateAdminPunishmentNotice(
                    jsonData, gaozhiType, null);
            return Result.success(result);
        } catch (Exception e) {
            log.error("生成行政处罚告知笔录失败", e);
            return Result.error("生成行政处罚告知笔录失败: " + e.getMessage());
        }
    }

    // 生成行政处罚告知笔录（从文件）
    @Operation(summary = "生成行政处罚告知笔录（从文件上传）")
    @PostMapping("/generation-gaozhi-from-file")
    public Result<Map<String, Object>> generationGaozhiFromFile(
            @RequestParam("caseApprovalFile") MultipartFile caseApprovalFile,
            @RequestParam("interrogationFile") MultipartFile interrogationFile,
            @RequestParam("gaozhiType") String gaozhiType,
            HttpServletResponse response) {
        try {
            if (caseApprovalFile == null || caseApprovalFile.isEmpty()) {
                return Result.error("立案审批表文件不能为空");
            }

            if (interrogationFile == null || interrogationFile.isEmpty()) {
                return Result.error("询问笔录文件不能为空");
            }

            if (gaozhiType == null || gaozhiType.isEmpty()) {
                return Result.error("缺少告知类型参数");
            }

            if (!gaozhiType.equals("处罚前告知") && !gaozhiType.equals("听证告知")) {
                return Result.error("告知类型参数错误，必须是\"处罚前告知\"或\"听证告知\"");
            }

            Map<String, Object> result = adminPunishmentNoticeService.generateAdminPunishmentNoticeFromFile(
                    caseApprovalFile, interrogationFile, gaozhiType, null);
            return Result.success(result);
        } catch (Exception e) {
            log.error("生成行政处罚告知笔录失败", e);
            return Result.error("生成行政处罚告知笔录失败: " + e.getMessage());
        }
    }

    /**
     * 下载生成的文件
     */
    @Operation(summary = "下载生成的文件")
    @GetMapping("/generated/{fileName:.+}")
    public void downloadGeneratedFile(
            @PathVariable String fileName,
            HttpServletResponse response) throws IOException {

        log.info("下载生成文件: {}", fileName);

        Path filePath = Paths.get(GENERATED_DIR, fileName);

        if (!Files.exists(filePath)) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        try (FileInputStream fis = new FileInputStream(filePath.toFile())) {
            fis.transferTo(response.getOutputStream());
            response.getOutputStream().flush();
        }
    }

}
